class SidebarMenu extends HTMLElement {
    constructor() {
        super();
        this.menuData = null;
        this.expanded = true;
        this.activeItem = null;
        this.templateUrl = '/components/sidebar/menu/index.html';
        this.templateId = 'wcs-sidebar-menu';
        this.loadData();
        this.init();
    }
    loadData() {
        const configScript = this.querySelector('script[type="application/json"]');
        this.configData = configScript ? JSON.parse(configScript.textContent) : { menuData: [] };
        this.menuData = this.configData.menuData;
        this.collapseAll = this.configData.collapseAll;
        this.cssStyle = this.configData.cssStyle || ":host{background: transparent;}";
        this.collapseIcon = this.configData.collapseIcon;
        eval(this.collapseAll)
    }
    connectedCallback() {
    }
    update() {
        let style = document.createElement("style");
        this.shadowRoot.appendChild(style);
        // 添加CSS规则
        style.textContent = this.cssStyle; // 直接设置 CSS 内容
        // 延迟等待样式表初始化
        // setTimeout(() => {
        //     if (style.sheet) {
        //         style.sheet.insertRule(this.cssStyle, 0);
        //     } else {
        //         console.error("样式表未就绪");
        //     }
        // }, 0);
        this.shadowRoot.getElementById("menu-content").innerHTML =
            `
            ${this.menuData?.search ? `
                    <div class="search-box">
                        <input type="text" placeholder="搜索..." id="search-input">
                        <div class="collapse-box" id="collapse-btn">
                            ${this.collapseIcon}
                        </div>
                    </div>
                ` : ''}
                <div class="menu-items">
                    ${this.renderMenuItems(this.menuData.items)}
                </div>
        `
    }
    // 更新内容的方法
    async init() {
        const template = await this.getTemplate();
        // 创建 Shadow DOM
        const shadow = this.attachShadow({ mode: 'open' });
        // 克隆模板内容并添加到 Shadow DOM
        const templateContent = await template.cloneNode(true);
        await shadow.appendChild(templateContent);
        this.update();
        this.addEventListeners();
        this.addEventListener('contract-menu-event', (e) => {
            // this.shadowRoot.querySelector('div').textContent = `Message received: ${e.detail.message}`;
            this.shadowRoot.getElementById("menu-content").classList.add("contract");
        });
        this.addEventListener('expand-menu-event', (e) => {
            // this.shadowRoot.querySelector('div').textContent = `Message received: ${e.detail.message}`;
            this.shadowRoot.getElementById("menu-content").classList.remove("contract");
        });
    }
    getTemplate() {
        const template = fetch(this.templateUrl)
            .then(response => response.text())
            .then(data => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                const template = doc.getElementById(this.templateId).content;
                return template;
            });
        return template;
    }
    renderMenuItems(items = [], level = 0) {
        return items.map(item => `
                    <div class="menu-item" 
                         data-level="${level}" 
                         data-has-children="${!!(item.children?.length)}">
                        <span><span class="icon">${item.icon}</span>
                        <span class="title">${item.title}</span>
                        ${item.children?.length ? '<span class="arrow">▸</span>' : ''}
                        ${item.children?.length ? `
                        </span>
                            <div class="children">
                                ${this.renderMenuItems(item.children, level + 1)}
                            </div>
                        ` : ''}
                    </div>
                `).join('');
    }

    addEventListeners() {
        this.shadowRoot.addEventListener('click', e => {
            const menuItem = e.target.closest('.menu-item');

            if (!menuItem) return;

            if (menuItem.dataset.hasChildren === 'true') {
                menuItem.classList.toggle('expanded');

                // if (!e.altKey && this.expanded) {
                //     const siblings = Array.from(menuItem.parentElement.children)
                //         .filter(child => child !== menuItem);
                //     siblings.forEach(sib => {
                //         sib.classList.remove('expanded');
                //     });

                // }
            } else {
                console.log('选中菜单:', menuItem.querySelector('.title').textContent);
                const event = new CustomEvent('open-menu-event', { detail: { menuItem: menuItem } });
                document.dispatchEvent(event);
                // this.setActiveItem(menuItem);
            }
        });

        // this.shadowRoot.addEventListener('dblclick', e => {
        //     if (e.target.closest('.menu-item')) {
        //         this.shadowRoot.querySelectorAll('.expanded').forEach(el => {
        //             el.classList.remove('expanded');
        //         });
        //     }
        // });

        if (this.menuData?.search) {
            this.shadowRoot.getElementById('search-input').addEventListener('input', (e) => {
                this.filterMenuItems(e.target.value.toLowerCase());
            });
        }
        if (this.menuData?.collapse) {
            this.shadowRoot.getElementById('collapse-btn').addEventListener('click', (e) => {
                this.shadowRoot.querySelectorAll('.expanded').forEach(el => {
                    el.classList.remove('expanded');
                });
            });
        }
    }

    filterMenuItems(searchTerm) {
        const allItems = this.shadowRoot.querySelectorAll('.menu-item');
        let hasMatches = false;
        if (searchTerm) {
            this.shadowRoot.querySelectorAll('.expanded').forEach(el => {
                el.classList.remove('expanded');
            });
        }
        // 第一步：标记所有匹配项
        allItems.forEach(item => {
            const title = item.querySelector('.title')?.textContent.toLowerCase() || '';
            const isMatch = searchTerm && title.includes(searchTerm);
            if (isMatch) {
                hasMatches = true;
            }
            item.isMatch = isMatch; // 自定义属性标记匹配状态
        });
        if (!hasMatches) { return; }

        // 第二步：向上传播匹配状态
        allItems.forEach(item => {
            if (item.isMatch) {
                let parent = item.parentElement.closest('.menu-item');
                while (parent) {
                    parent.isMatch = true;
                    parent = parent.parentElement.closest('.menu-item');
                }
            }
        });

        // 第三步：更新显示状态
        allItems.forEach(item => {
            const shouldShow = item.isMatch || this.hasMatchingChild(item);
            if (shouldShow) {
                this.expandParentMenus(item);
            }
        });
    }

    hasMatchingChild(item) {
        const children = item.querySelector('.children')?.children || [];
        return Array.from(children).some(child => {
            return child.style.visibility == 'visible' || this.hasMatchingChild(child);
        });
    }

    expandParentMenus(item) {
        let parent = item.parentElement.closest('.menu-item');
        while (parent) {
            parent.classList.add('expanded');
            parent = parent.parentElement.closest('.menu-item');
        }
    }

    setActiveItem(menuItem) {
        this.activeItem?.classList.remove('active');
        menuItem.classList.add('active');
        this.activeItem = menuItem;
    }
}

customElements.define('wcs-sidebar-menu', SidebarMenu);